package com.framework.common.xss;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * XSS过滤
 */
public class XssFilter implements Filter {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String url = httpServletRequest.getRequestURI();
		String method = httpServletRequest.getMethod();
		String query = httpServletRequest.getQueryString();
		Pattern ptn = Pattern.compile("(.css|.js|.woff|.png|.jpg|.ico)");
		Matcher m = ptn.matcher(url);
		if (!m.find()) {
			logger.info(String.format("%s : %s%s", method.toUpperCase(), url, query == null ? "" : "?" + query));
		}
		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(httpServletRequest);
		chain.doFilter(xssRequest, response);
	}

	@Override
	public void destroy() {

	}
}